package com.zhao.dome01.utils;

import org.springframework.cglib.beans.BeanMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//在bean和map两种类型之间进行相互转换
public class TypeChange {

    public static  <T> Map<String,Object> beanToMap(T bean){
        Map<String, Object> map = new HashMap<>();
        if (bean != null){
            //这里是重点  可以将bean转化为BeanMao对象
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key:beanMap.keySet()){
                map.put(key+"",beanMap.get(key));
            }
        }
        return map;
    }

    public static <T> T mapToBean(Map<String,Object> map,T bean){
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    public static <T> List<Map<String,Object>> listBeanToMaps(List<T> beanList){
        List<Map<String, Object>> list = new ArrayList<>();
        if (beanList != null && beanList.size() > 0){
            Map<String,Object> map = null;
            T bean = null;
            for (int i = 0,size = beanList.size(); i < size;i++){
                bean = beanList.get(i);
                map = beanToMap(bean);
                list.add(map);
            }
        }
        return list;
    }

    public static <T> List<T> listMapsToBeans(List<Map<String, Object>> maps,Class<T> clazz) throws InstantiationException, IllegalAccessException {
        List<T> list = new ArrayList<>();
        if (maps != null && maps.size() > 0) {
            Map<String, Object> map = null;
            T bean = null;
            for (int i = 0, size = maps.size(); i < size; i++) {
                map = maps.get(i);
                bean = clazz.newInstance();
                mapToBean(map, bean);
                list.add(bean);
            }
        }
        return list;
    }
}
